package com.neusoft.hifly.information.article.api;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;

import com.neusoft.hifly.commons.exception.SystemErrorException;
import com.neusoft.hifly.commons.lang.LongUtil;
import com.neusoft.hifly.core.pojo.ApiCode;
import com.neusoft.hifly.core.pojo.ApiResponse;
import com.neusoft.hifly.core.token.TokenContextHolder;
import com.neusoft.hifly.core.utils.GlobalConstants;
import com.neusoft.hifly.information.article.domain.StatusVO;
import com.neusoft.hifly.information.article.entity.ArticleExtObj;
import com.neusoft.hifly.information.article.entity.ArticleInfoObj;
import com.neusoft.hifly.information.article.entity.ArticleObj;
import com.neusoft.hifly.information.article.service.IArticleLogService;
import com.neusoft.hifly.information.article.service.IArticleService;
import com.neusoft.hifly.information.column.entity.ColumnObj;
import com.neusoft.hifly.information.column.service.IColumnService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * Title: 文章资讯服务-文章资讯
 * <p>
 * Description: 文章 接口
 * <p>
 * Copyright: 2019
 * <p>
 * Company: 东软汉枫
 *
 * @author lh_neu
 * @version 1.0.0
 */
@CrossOrigin
@RestController
@RequestMapping("/api/v1/article")
@Api(value = "article-api", description = "文章接口")
public class ArticleApi {
	@Autowired(required = false)
	private IArticleService articleService;
	@Autowired(required = false)
	private IColumnService columnService;
	@Autowired(required = false)
	private IArticleLogService articleLogService;

	/**
	 * 查询所有数据
	 *
	 * @return 集合
	 */
	@ApiOperation("查询文章集合")
	@GetMapping(value = "/list")
	public ApiResponse<?> findAll() {
		final String organCode = TokenContextHolder.get().getOrganCode();
		final long organLogicId = TokenContextHolder.get().getOrganLogicId();

		if (StringUtils.isEmpty(organCode) || LongUtil.isEmpty(organLogicId)) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "参数错误!");
		}
		return new ApiResponse<>(ApiCode.SUCCESS.getCode(), "成功！", articleService.findAll(organCode, organLogicId));
	}

	/**
	 * 文章查询
	 *
	 * @param HttpServletRequest
	 *            request
	 * @return 集合
	 */
	@ApiOperation("文章查询")
	@ApiImplicitParams({ @ApiImplicitParam(name = "offset", value = "开始索引", dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "limit", value = "每页纪录数", dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "title", value = "标题", dataType = "String", paramType = "query") })
	@GetMapping(value = "/search")
	public ApiResponse<?> search(final HttpServletRequest request) {
		final String organCode = TokenContextHolder.get().getOrganCode();
		final long organLogicId = TokenContextHolder.get().getOrganLogicId();

		if (StringUtils.isEmpty(organCode) || LongUtil.isEmpty(organLogicId)) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "参数错误!");
		}

		final String offsetStr = StringUtils.trimToEmpty(request.getParameter("offset"));
		final String limitStr = StringUtils.trimToEmpty(request.getParameter("limit"));
		int offset = GlobalConstants.PAGE_OFFSET;
		int limit = GlobalConstants.PAGE_LIMIT;
		if (StringUtils.isNotEmpty(offsetStr) && StringUtils.isNumeric(offsetStr)) {
			offset = Integer.parseInt(offsetStr);
		}
		if (StringUtils.isNotEmpty(limitStr) && StringUtils.isNumeric(limitStr)) {
			limit = Integer.parseInt(limitStr);
		}

		// 参数
		final Map<String, Object> params = new HashMap<String, Object>(0);

		// 添加搜索
		searchWhere(request, params);

		final IPage<ArticleObj> page = articleService.search(organCode, organLogicId, offset, limit, params);

		return new ApiResponse<>(ApiCode.SUCCESS.getCode(), "成功！", page);
	}

	/**
	 * 编辑文章列表
	 *
	 * @param HttpServletRequest
	 *            request
	 * @return 集合
	 */
	@ApiOperation("编辑文章列表")
	@ApiImplicitParams({ @ApiImplicitParam(name = "offset", value = "开始索引", dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "limit", value = "每页纪录数", dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "title", value = "标题", dataType = "String", paramType = "query") })
	@GetMapping(value = "/editSearch")
	public ApiResponse<?> editSearch(final HttpServletRequest request) {
		final String organCode = TokenContextHolder.get().getOrganCode();
		final long organLogicId = TokenContextHolder.get().getOrganLogicId();
		final long userLogicId = TokenContextHolder.get().getUserLogicId();

		if (StringUtils.isEmpty(organCode) || LongUtil.isEmpty(organLogicId) || LongUtil.isEmpty(userLogicId)) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "参数错误!");
		}

		final String offsetStr = StringUtils.trimToEmpty(request.getParameter("offset"));
		final String limitStr = StringUtils.trimToEmpty(request.getParameter("limit"));
		int offset = GlobalConstants.PAGE_OFFSET;
		int limit = GlobalConstants.PAGE_LIMIT;
		if (StringUtils.isNotEmpty(offsetStr) && StringUtils.isNumeric(offsetStr)) {
			offset = Integer.parseInt(offsetStr);
		}
		if (StringUtils.isNotEmpty(limitStr) && StringUtils.isNumeric(limitStr)) {
			limit = Integer.parseInt(limitStr);
		}

		// 参数
		final Map<String, Object> params = new HashMap<String, Object>(0);

		// 编辑状态
		params.put("status", ArticleObj.STATUS_0);
		params.put("createPersonId", userLogicId);

		// 添加搜索
		searchWhere(request, params);

		final IPage<ArticleObj> page = articleService.search(organCode, organLogicId, offset, limit, params);

		return new ApiResponse<>(ApiCode.SUCCESS.getCode(), "成功！", page);
	}

	/**
	 * 校对文章列表
	 *
	 * @param HttpServletRequest
	 *            request
	 * @return 集合
	 */
	@ApiOperation("校对文章列表")
	@ApiImplicitParams({ @ApiImplicitParam(name = "offset", value = "开始索引", dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "limit", value = "每页纪录数", dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "title", value = "标题", dataType = "String", paramType = "query") })
	@GetMapping(value = "/proofSearch")
	public ApiResponse<?> proofSearch(final HttpServletRequest request) {
		final String organCode = TokenContextHolder.get().getOrganCode();
		final long organLogicId = TokenContextHolder.get().getOrganLogicId();

		if (StringUtils.isEmpty(organCode) || LongUtil.isEmpty(organLogicId)) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "参数错误!");
		}

		final String offsetStr = StringUtils.trimToEmpty(request.getParameter("offset"));
		final String limitStr = StringUtils.trimToEmpty(request.getParameter("limit"));
		int offset = GlobalConstants.PAGE_OFFSET;
		int limit = GlobalConstants.PAGE_LIMIT;
		if (StringUtils.isNotEmpty(offsetStr) && StringUtils.isNumeric(offsetStr)) {
			offset = Integer.parseInt(offsetStr);
		}
		if (StringUtils.isNotEmpty(limitStr) && StringUtils.isNumeric(limitStr)) {
			limit = Integer.parseInt(limitStr);
		}

		// 参数
		final Map<String, Object> params = new HashMap<String, Object>(0);

		// 编辑状态
		params.put("status", ArticleObj.STATUS_1);

		// 添加搜索
		searchWhere(request, params);

		final IPage<ArticleObj> page = articleService.search(organCode, organLogicId, offset, limit, params);

		return new ApiResponse<>(ApiCode.SUCCESS.getCode(), "成功！", page);
	}

	/**
	 * 审核文章列表
	 *
	 * @param HttpServletRequest
	 *            request
	 * @return 集合
	 */
	@ApiOperation("审核文章列表")
	@ApiImplicitParams({ @ApiImplicitParam(name = "offset", value = "开始索引", dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "limit", value = "每页纪录数", dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "title", value = "标题", dataType = "String", paramType = "query") })
	@GetMapping(value = "/approveSearch")
	public ApiResponse<?> approveSearch(final HttpServletRequest request) {
		final String organCode = TokenContextHolder.get().getOrganCode();
		final long organLogicId = TokenContextHolder.get().getOrganLogicId();

		if (StringUtils.isEmpty(organCode) || LongUtil.isEmpty(organLogicId)) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "参数错误!");
		}

		final String offsetStr = StringUtils.trimToEmpty(request.getParameter("offset"));
		final String limitStr = StringUtils.trimToEmpty(request.getParameter("limit"));
		int offset = GlobalConstants.PAGE_OFFSET;
		int limit = GlobalConstants.PAGE_LIMIT;
		if (StringUtils.isNotEmpty(offsetStr) && StringUtils.isNumeric(offsetStr)) {
			offset = Integer.parseInt(offsetStr);
		}
		if (StringUtils.isNotEmpty(limitStr) && StringUtils.isNumeric(limitStr)) {
			limit = Integer.parseInt(limitStr);
		}

		// 参数
		final Map<String, Object> params = new HashMap<String, Object>(0);

		// 编辑状态
		params.put("status", ArticleObj.STATUS_2);

		// 添加搜索
		searchWhere(request, params);

		final IPage<ArticleObj> page = articleService.search(organCode, organLogicId, offset, limit, params);

		return new ApiResponse<>(ApiCode.SUCCESS.getCode(), "成功！", page);
	}

	/**
	 * 已发布文章列表
	 *
	 * @param HttpServletRequest
	 *            request
	 * @return 集合
	 */
	@ApiOperation("已发布文章列表")
	@ApiImplicitParams({ @ApiImplicitParam(name = "offset", value = "开始索引", dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "limit", value = "每页纪录数", dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "title", value = "标题", dataType = "String", paramType = "query") })
	@GetMapping(value = "/publishSearch")
	public ApiResponse<?> publishSearch(final HttpServletRequest request) {
		final String organCode = TokenContextHolder.get().getOrganCode();
		final long organLogicId = TokenContextHolder.get().getOrganLogicId();

		if (StringUtils.isEmpty(organCode) || LongUtil.isEmpty(organLogicId)) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "参数错误!");
		}

		final String offsetStr = StringUtils.trimToEmpty(request.getParameter("offset"));
		final String limitStr = StringUtils.trimToEmpty(request.getParameter("limit"));
		int offset = GlobalConstants.PAGE_OFFSET;
		int limit = GlobalConstants.PAGE_LIMIT;
		if (StringUtils.isNotEmpty(offsetStr) && StringUtils.isNumeric(offsetStr)) {
			offset = Integer.parseInt(offsetStr);
		}
		if (StringUtils.isNotEmpty(limitStr) && StringUtils.isNumeric(limitStr)) {
			limit = Integer.parseInt(limitStr);
		}

		// 参数
		final Map<String, Object> params = new HashMap<String, Object>(0);

		// 编辑状态
		params.put("status", ArticleObj.STATUS_3);

		// 添加搜索
		searchWhere(request, params);

		final IPage<ArticleObj> page = articleService.search(organCode, organLogicId, offset, limit, params);

		return new ApiResponse<>(ApiCode.SUCCESS.getCode(), "成功！", page);
	}

	/**
	 * 通过逻辑ID获取文章
	 *
	 * @param HttpServletRequest
	 *            request
	 * @return 文章信息
	 */
	@ApiOperation("通过逻辑ID获取文章")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "logicId", value = "文章逻辑ID", dataType = "long", paramType = "path", required = true) })
	@GetMapping(value = "/{logicId}")
	public ApiResponse<?> getByLogicId(@PathVariable("logicId") final long logicId) {
		final String organCode = TokenContextHolder.get().getOrganCode();
		final long organLogicId = TokenContextHolder.get().getOrganLogicId();

		if (StringUtils.isEmpty(organCode) || LongUtil.isEmpty(organLogicId) || LongUtil.isEmpty(logicId)) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "参数错误!");
		}
		final ArticleObj obj = articleService.getByLogicId(organCode, organLogicId, logicId);
		if (obj == null) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "数据不存在！");
		}
		return new ApiResponse<>(ApiCode.SUCCESS.getCode(), "成功！", obj);
	}

	/**
	 * 通过逻辑ID删除文章
	 *
	 * @param logicId
	 *            文章ID，多id使用英文逗号分隔
	 * @return 成功信息
	 */
	@ApiOperation("通过逻辑ID删除文章")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "logicId", value = "文章ID，多id使用英文逗号分隔", dataType = "string", paramType = "path", required = true) })
	@DeleteMapping(value = "/{logicId}")
	public ApiResponse<?> delete(@PathVariable("logicId") final String logicId) {
		final String organCode = TokenContextHolder.get().getOrganCode();
		final long organLogicId = TokenContextHolder.get().getOrganLogicId();

		if (StringUtils.isEmpty(organCode) || LongUtil.isEmpty(organLogicId) || StringUtils.isEmpty(logicId)) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "参数错误!");
		}
		articleService.deleteByBatch(organCode, organLogicId, logicId);
		return new ApiResponse<>(ApiCode.SUCCESS.getCode(), "成功！");
	}

	/**
	 * 初始化新增
	 *
	 * @param columnLogicId
	 *            逻辑ID
	 * @return 栏目信息
	 */
	@ApiOperation("初始化新增")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "columnLogicId", value = "逻辑ID", dataType = "long", paramType = "path", required = true) })
	@GetMapping(value = "/initSave/{columnLogicId}")
	public ApiResponse<?> initSave(@PathVariable("columnLogicId") final long columnLogicId) {
		final String organCode = TokenContextHolder.get().getOrganCode();
		final long organLogicId = TokenContextHolder.get().getOrganLogicId();
		final long userLogicId = TokenContextHolder.get().getUserLogicId();

		if (StringUtils.isEmpty(organCode) || LongUtil.isEmpty(organLogicId)) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "参数错误!");
		}

		final Map<String, Object> result = new HashMap<String, Object>(2);

		// 初始化一些数据
		final ArticleObj obj = new ArticleObj();

		final ArticleInfoObj info = new ArticleInfoObj();
		info.setOrganCode(obj.getOrganCode());
		info.setOrganLogicId(obj.getOrganLogicId());
		info.setArticleLogicId(obj.getLogicId());
		obj.setInfo(info);
		final ArticleExtObj ext = new ArticleExtObj();
		ext.setOrganCode(obj.getOrganCode());
		ext.setOrganLogicId(obj.getOrganLogicId());
		ext.setArticleLogicId(obj.getLogicId());
		obj.setExt(ext);

		String articleTemplate = ColumnObj.TEMPLATE_DEF;
		if (GlobalConstants.ABS_ID != columnLogicId) {
			final ColumnObj col = columnService.getByLogicId(organCode, organLogicId, columnLogicId, true, userLogicId);
			if (col != null) {
				obj.setColumnLogicId(columnLogicId);
				obj.setColumnName(col.getName());
				// 文章模板
				articleTemplate = col.getExt1();
			} else {
				return new ApiResponse<>(ApiCode.ERROR.getCode(), "您没有该栏目的权限!");
			}
		}
		obj.setArticleTemplate(articleTemplate);
		result.put("obj", obj);
		result.put("columns", columnService.findNodes(organCode, organLogicId, userLogicId));
		return new ApiResponse<>(ApiCode.SUCCESS.getCode(), "成功！", result);
	}

	/**
	 * 初始化编辑
	 *
	 * @param logicId
	 *            文章逻辑ID
	 * @return 文章信息
	 */
	@ApiOperation("初始化编辑")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "logicId", value = "文章逻辑ID", dataType = "long", paramType = "path", required = true) })
	@GetMapping(value = "/initEdit/{logicId}")
	public ApiResponse<?> initEdit(@PathVariable("logicId") final long logicId) {
		final String organCode = TokenContextHolder.get().getOrganCode();
		final long organLogicId = TokenContextHolder.get().getOrganLogicId();
		final long userLogicId = TokenContextHolder.get().getUserLogicId();

		if (StringUtils.isEmpty(organCode) || LongUtil.isEmpty(organLogicId) || LongUtil.isEmpty(logicId)) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "参数错误!");
		}
		final ArticleObj obj = articleService.getByLogicId(organCode, organLogicId, logicId);
		if (obj == null) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "数据不存在！");
		}

		final Map<String, Object> result = new HashMap<String, Object>(2);

		String articleTemplate = ColumnObj.TEMPLATE_DEF;
		if (GlobalConstants.ABS_ID != obj.getColumnLogicId()) {
			final ColumnObj col = columnService.getByLogicId(organCode, organLogicId, obj.getColumnLogicId(), true,
					userLogicId);
			if (col != null) {
				obj.setColumnLogicId(obj.getColumnLogicId());
				obj.setColumnName(col.getName());
				// 文章模板
				articleTemplate = col.getExt1();
			} else {
				return new ApiResponse<>(ApiCode.ERROR.getCode(), "您没有该栏目的权限!");
			}
		}
		obj.setArticleTemplate(articleTemplate);

		result.put("obj", obj);

		result.put("columns", columnService.findNodes(organCode, organLogicId, userLogicId));

		result.put("logs", articleLogService.findByArticleId(organCode, organLogicId, obj.getLogicId()));

		return new ApiResponse<>(ApiCode.SUCCESS.getCode(), "成功！", result);
	}

	/**
	 * 提交文章（走流程）
	 *
	 * @param obj
	 *            文章信息
	 * @return 文章信息
	 */
	@ApiOperation("提交文章（走流程）")
	@ApiImplicitParams({ @ApiImplicitParam(name = "obj", value = "文章信息", dataType = "ArticleObj", required = true) })
	@PostMapping(value = "/submit")
	public ApiResponse<?> submit(@RequestBody final ArticleObj obj) {
		final String organCode = TokenContextHolder.get().getOrganCode();
		final long organLogicId = TokenContextHolder.get().getOrganLogicId();

		if (StringUtils.isEmpty(organCode) || LongUtil.isEmpty(organLogicId) || obj == null) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "参数错误!");
		}
		try {
			articleService.saveOrUpdate(organCode, organLogicId, obj, false);
		} catch (final SystemErrorException e) {
			return new ApiResponse<>(e);
		}
		return new ApiResponse<>(ApiCode.SUCCESS.getCode(), "成功！");
	}

	/**
	 * 新增文章
	 *
	 * @param obj
	 *            文章信息
	 * @return 文章信息
	 */
	@ApiOperation("新增文章")
	@ApiImplicitParams({ @ApiImplicitParam(name = "obj", value = "文章信息", dataType = "ArticleObj", required = true) })
	@PostMapping(value = "")
	public ApiResponse<?> save(@RequestBody final ArticleObj obj) {
		final String organCode = TokenContextHolder.get().getOrganCode();
		final long organLogicId = TokenContextHolder.get().getOrganLogicId();

		if (StringUtils.isEmpty(organCode) || LongUtil.isEmpty(organLogicId) || obj == null) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "参数错误!");
		}
		try {
			articleService.saveOrUpdate(organCode, organLogicId, obj, true);
		} catch (final SystemErrorException e) {
			return new ApiResponse<>(e);
		}
		return new ApiResponse<>(ApiCode.SUCCESS.getCode(), "成功！");
	}

	/**
	 * 更新文章
	 *
	 * @param obj
	 *            文章信息
	 * @return 文章信息
	 */
	@ApiOperation("更新文章")
	@ApiImplicitParams({ @ApiImplicitParam(name = "obj", value = "文章信息", dataType = "ArticleObj", required = true) })
	@PutMapping(value = "")
	public ApiResponse<?> update(@RequestBody final ArticleObj obj) {
		final String organCode = TokenContextHolder.get().getOrganCode();
		final long organLogicId = TokenContextHolder.get().getOrganLogicId();

		if (StringUtils.isEmpty(organCode) || LongUtil.isEmpty(organLogicId) || obj == null) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "参数错误!");
		}

		final ArticleObj oldObj = articleService.getByLogicId(organCode, organLogicId, obj.getLogicId());
		if (oldObj == null) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "文章不存在！");
		}
		try {
			articleService.saveOrUpdate(organCode, organLogicId, obj, true);
		} catch (final SystemErrorException e) {
			return new ApiResponse<>(e);
		}
		return new ApiResponse<>(ApiCode.SUCCESS.getCode(), "成功！");
	}

	/**
	 * 更新文章状态
	 *
	 * @param obj
	 *            状态信息
	 * @return 文章信息
	 */
	@ApiOperation("更新文章状态")
	@ApiImplicitParams({ @ApiImplicitParam(name = "obj", value = "状态信息", dataType = "StatusVO", required = true) })
	@PutMapping(value = "/status")
	public ApiResponse<?> updateStatus(@RequestBody final StatusVO obj) {
		final String organCode = TokenContextHolder.get().getOrganCode();
		final long organLogicId = TokenContextHolder.get().getOrganLogicId();
		final String logicIds = obj.getLogicIds();
		final String status = obj.getStatus();

		if (StringUtils.isEmpty(organCode) || LongUtil.isEmpty(organLogicId) || StringUtils.isEmpty(logicIds)
				|| StringUtils.isEmpty(status)) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "参数错误!");
		}

		articleService.updateStatus(organCode, organLogicId, logicIds, status);
		return new ApiResponse<>(ApiCode.SUCCESS.getCode(), "成功！");
	}

	/**
	 * 搜索条件
	 *
	 * @param request
	 *            HttpServletRequest
	 * @param property
	 *            参数
	 */
	private void searchWhere(final HttpServletRequest request, final Map<String, Object> property) {
		boolean isLike = false;
		final String title = StringUtils.trimToEmpty(request.getParameter("title"));
		if (StringUtils.isNotEmpty(title)) {
			property.put("title", title);
			isLike = true;
		}
		final String columnName = StringUtils.trimToEmpty(request.getParameter("columnName"));
		if (StringUtils.isNotEmpty(columnName)) {
			property.put("columnName", columnName);
			isLike = true;
		}
		property.put("isLike", isLike);
	}

}